//==================================================================
//  Copyright (C) 2006-2007  Davide Pasca
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License, or (at your option) any later version.
//
//  This library is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//  Lesser General Public License for more details.
//
//  You should have received a copy of the GNU Lesser General Public
//  License along with this library; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//==================================================================
/// @file image_base_jpeg.h
///
///
/// @author Davide Pasca
///
//==================================================================

#include "image_base.h"
#include <setjmp.h>
#define XMD_H	// yeah, whatever !
#include "../../externals/jpeglib/jinclude.h"
#include "../../externals/jpeglib/jpeglib.h"
#include "../../externals/jpeglib/jerror.h"


/*
* memsrc.c
*
* Copyright (C) 1994-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains decompression data source routines for the case of
* reading JPEG data from a memory buffer that is preloaded with the entire
* JPEG file. This would not seem especially useful at first sight, but
* a number of people have asked for it.
* This is really just a stripped-down version of jdatasrc.c. Comparison
* of this code with jdatasrc.c may be helpful in seeing how to make
* custom source managers for other purposes.
*/

/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
//#include "jinclude.h"
//#include "jpeglib.h"
//#include "jerror.h"


/* Expanded data source object for memory input */

typedef struct {
	struct jpeg_source_mgr pub; /* public fields */

	JOCTET eoi_buffer[2]; /* a place to put a dummy EOI */
} my_source_mgr;

typedef my_source_mgr * my_src_ptr;


/*
* Initialize source --- called by jpeg_read_header
* before any data is actually read.
*/

METHODDEF(void)
init_source (j_decompress_ptr cinfo)
{
	/* No work, since jpeg_memory_src set up the buffer pointer and count.
	* Indeed, if we want to read multiple JPEG images from one buffer,
	* this *must* not do anything to the pointer.
	*/
}


/*
* Fill the input buffer --- called whenever buffer is emptied.
*
* In this application, this routine should never be called; if it is called,
* the decompressor has overrun the end of the input buffer, implying we
* supplied an incomplete or corrupt JPEG datastream. A simple error exit
* might be the most appropriate response.
*
* But what we choose to do in this code is to supply dummy EOI markers
* in order to force the decompressor to finish processing and supply
* some sort of output image, no matter how corrupted.
*/

METHODDEF(boolean)
fill_input_buffer (j_decompress_ptr cinfo)
{
	my_src_ptr src = (my_src_ptr) cinfo->src;

	WARNMS(cinfo, JWRN_JPEG_EOF);

	/* Create a fake EOI marker */
	src->eoi_buffer[0] = (JOCTET) 0xFF;
	src->eoi_buffer[1] = (JOCTET) JPEG_EOI;
	src->pub.next_input_byte = src->eoi_buffer;
	src->pub.bytes_in_buffer = 2;

	return TRUE;
}


/*
* Skip data --- used to skip over a potentially large amount of
* uninteresting data (such as an APPn marker).
*
* If we overrun the end of the buffer, we let fill_input_buffer deal with
* it. An extremely large skip could cause some time-wasting here, but
* it really isn't supposed to happen ... and the decompressor will never
* skip more than 64K anyway.
*/

METHODDEF(void)
skip_input_data (j_decompress_ptr cinfo, long num_bytes)
{
	my_src_ptr src = (my_src_ptr) cinfo->src;

	if (num_bytes > 0) {
		while (num_bytes > (long) src->pub.bytes_in_buffer) {
			num_bytes -= (long) src->pub.bytes_in_buffer;
			(void) fill_input_buffer(cinfo);
			/* note we assume that fill_input_buffer will never return FALSE,
			* so suspension need not be handled.
			*/
		}
		src->pub.next_input_byte += (size_t) num_bytes;
		src->pub.bytes_in_buffer -= (size_t) num_bytes;
	}
}


/*
* An additional method that can be provided by data source modules is the
* resync_to_restart method for error recovery in the presence of RST markers.
* For the moment, this source module just uses the default resync method
* provided by the JPEG library. That method assumes that no backtracking
* is possible.
*/


/*
* Terminate source --- called by jpeg_finish_decompress
* after all data has been read. Often a no-op.
*
* NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
* application must deal with any cleanup that should happen even
* for error exit.
*/

METHODDEF(void)
term_source (j_decompress_ptr cinfo)
{
	/* no work necessary here */
}


/*
* Prepare for input from a memory buffer.
*/

GLOBAL(void)
jpeg_memory_src (j_decompress_ptr cinfo, const JOCTET * buffer, size_t bufsize)
{
	my_src_ptr src;

	/* The source object is made permanent so that a series of JPEG images
	* can be read from a single buffer by calling jpeg_memory_src
	* only before the first one.
	* This makes it unsafe to use this manager and a different source
	* manager serially with the same JPEG object. Caveat programmer.
	*/
	if (cinfo->src == NULL) { /* first time for this JPEG object? */
		cinfo->src = (struct jpeg_source_mgr *)
			(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
			SIZEOF(my_source_mgr));
	}

	src = (my_src_ptr) cinfo->src;
	src->pub.init_source = init_source;
	src->pub.fill_input_buffer = fill_input_buffer;
	src->pub.skip_input_data = skip_input_data;
	src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
	src->pub.term_source = term_source;

	src->pub.next_input_byte = buffer;
	src->pub.bytes_in_buffer = bufsize;
}

//=============================================================================
struct my_error_mgr {
	struct jpeg_error_mgr pub;	/* "public" fields */

	jmp_buf setjmp_buffer;	/* for return to caller */
};

typedef struct my_error_mgr * my_error_ptr;

//=============================================================================
void my_error_exit (j_common_ptr cinfo)
{
	/* cinfo->err really points to a my_error_mgr struct, so coerce pointer */
	my_error_ptr myerr = (my_error_ptr) cinfo->err;

	/* Always display the message. */
	/* We could postpone this until after returning, if we chose. */
	(*cinfo->err->output_message) (cinfo);

	/* Return control to the setjmp point */
	longjmp(myerr->setjmp_buffer, 1);
}

//=============================================================================
typedef struct
{
	struct jpeg_destination_mgr pub;	/* public fields */
	JOCTET *buffer;                     /* start of buffer */
	int bufsize;                        /* buffer size */
	int datacount;                      /* finale data size */
} memory_destination_mgr;

typedef memory_destination_mgr *mem_dest_ptr;

//=============================================================================
// Initialize destination --- called by jpeg_start_compress before any data is actually written.
METHODDEF(void)
init_destination (j_compress_ptr cinfo)
{
  mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest;
  dest->pub.next_output_byte = dest->buffer;
  dest->pub.free_in_buffer = dest->bufsize;
  dest->datacount=0;
}

//=============================================================================
//  Empty the output buffer --- called whenever buffer fills up.
METHODDEF(boolean)
empty_output_buffer (j_compress_ptr cinfo)
{
  mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest;
  dest->pub.next_output_byte = dest->buffer;
  dest->pub.free_in_buffer = dest->bufsize;

  return TRUE;
}

//=============================================================================
// Terminate destination --- called by jpeg_finish_compress
// after all data has been written.  Usually needs to flush buffer.
METHODDEF(void)
term_destination (j_compress_ptr cinfo)
{
  /* expose the finale compressed image size */
  
  mem_dest_ptr dest = (mem_dest_ptr) cinfo->dest;
  dest->datacount = dest->bufsize - dest->pub.free_in_buffer;
  
}

//=============================================================================
GLOBAL(void)
jpeg_memory_dest(j_compress_ptr cinfo, JOCTET *buffer,int bufsize)
{
  mem_dest_ptr dest;
  if (cinfo->dest == NULL) {    /* first time for this JPEG object? */
    cinfo->dest = (struct jpeg_destination_mgr *)
      (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
                                  sizeof(memory_destination_mgr));
  }
  
  dest = (mem_dest_ptr) cinfo->dest;
  dest->bufsize=bufsize;
  dest->buffer=buffer;
  dest->pub.init_destination = init_destination;
  dest->pub.empty_output_buffer = empty_output_buffer;
  dest->pub.term_destination = term_destination;
}

//=============================================================================
///
//=============================================================================
namespace PUtils {

//=============================================================================
void ImageBase::LoadJPEG( Memfile &mf, LoadParams *paramsp )
{
    struct jpeg_decompress_struct cinfo;
    struct my_error_mgr jerr;

    /* We set up the normal JPEG error routines, then override error_exit. */
    cinfo.err = jpeg_std_error(&jerr.pub);
    jerr.pub.error_exit = my_error_exit;
    /* Establish the setjmp return context for my_error_exit to use. */
    if (setjmp(jerr.setjmp_buffer)) 
    {
        /* If we get here, the JPEG code has signaled an error.
        * We need to clean up the JPEG object, close the input file, and return.
        */
        jpeg_destroy_decompress(&cinfo);
		throw "JPEG file load failed";
    }
    /* Now we can initialize the JPEG decompression object. */
    jpeg_create_decompress(&cinfo);

	jpeg_memory_src( &cinfo, (const JOCTET *)mf.GetData(), mf.GetDataSize() );

	jpeg_read_header(&cinfo, TRUE);

	jpeg_start_decompress(&cinfo);

	/* JSAMPLEs per row in output buffer */
	int	row_stride = cinfo.output_width * cinfo.output_components;

	BaseFormat	dest_format = BF_NONE;
	BaseFormat	src_format = BF_NONE;

	switch ( cinfo.output_components )
	{
	case 1:
		dest_format = src_format = BF_L8;
		break;

	case 3:
		dest_format = src_format = BF_R8G8B8;
		break;

	default:
		throw "Unsupported JPEG format";
		break;
	}

	if ( paramsp && paramsp->_do_force_alpha )
	{
		dest_format = BF_R8G8B8A8;
	}

	Setup(	dest_format,
			cinfo.output_width,
			cinfo.output_height, NULL, 0 );

	/* Make a one-row-high sample array that will go away when done with image */
	JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1);

    int y = 0;
    while (cinfo.output_scanline < cinfo.output_height) 
    {
        jpeg_read_scanlines(&cinfo, buffer, 1);

		ImageBase	src_img( src_format, cinfo.output_width, 1, (u_char *)buffer[0], 0 );

		BlitFrom(	src_img, 0, 0,
					cinfo.output_width, 1,
					0, y );
        y++;
    }

    jpeg_finish_decompress(&cinfo);
    jpeg_destroy_decompress(&cinfo);
}


//=============================================================================
void ImageBase::SaveJPEG( const TCHAR *filename, int quality )
{
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE	*outfile;
JSAMPROW row_pointer[1];
int		row_stride;

	/* Step 1: allocate and initialize JPEG compression object */
	cinfo.err = jpeg_std_error(&jerr);
	jpeg_create_compress(&cinfo);

	/* Step 2: specify data destination (eg, a file) */
	if ( _tfopen_s( &outfile, filename, _T("wb") ) )
	{
		jpeg_destroy_compress(&cinfo);
		throw "Error trying to open the file fro writing";
	}
  
	jpeg_stdio_dest(&cinfo, outfile);

	/* Step 3: set parameters for compression */
	cinfo.image_width = GetWidth(); 	/* image width and height, in pixels */
	cinfo.image_height = GetHeight();

	switch ( GetBaseFormat() )
	{
	case BF_R8G8B8:
		cinfo.input_components = 3;
		break;

	case BF_B8G8R8:
		cinfo.input_components = 3;
		break;

	default:
		throw "Invalid source format";
	}
	cinfo.in_color_space = JCS_RGB; 	/* colorspace of input image */

	jpeg_set_defaults(&cinfo);
	// DAVIDE: ummm
	cinfo.dct_method = JDCT_FLOAT;

	jpeg_set_quality(&cinfo, quality, TRUE );

	/* Step 4: Start compressor */
	jpeg_start_compress(&cinfo, TRUE);

	row_stride = GetImagePitch();	/* JSAMPLEs per row in image_buffer */
	u_char	*image_buffer = GetData();

	while (cinfo.next_scanline < cinfo.image_height)
	{
		row_pointer[0] = &image_buffer[cinfo.next_scanline * row_stride];
		if ( jpeg_write_scanlines(&cinfo, row_pointer, 1) != 1 )
		{
			fclose( outfile );
			jpeg_destroy_compress(&cinfo);
			throw "Writing scanlines";
		}
	}

	jpeg_finish_compress(&cinfo);
	fclose( outfile );
	jpeg_destroy_compress(&cinfo);
}

//=============================================================================
void ImageBase::SaveJPEG( Memfile &memfile, int quality )
{
	struct jpeg_compress_struct cinfo;
	struct jpeg_error_mgr jerr;

	JOCTET *jpgbuff;

	// zero out the compression info structures and allocate a new compressor handle
	memset (&cinfo,0,sizeof(cinfo));
	cinfo.err = jpeg_std_error(&jerr);
	jpeg_create_compress(&cinfo);

	// Setup JPEG data structures
	cinfo.image_width = GetWidth();      /* image width and height, in pixels */
	cinfo.image_height = GetHeight();
	cinfo.input_components = 3;   /* # of color components per pixel=3 RGB */
	cinfo.in_color_space = JCS_RGB;

	memfile.SetDataSize( cinfo.image_width * cinfo.image_height * 3 );	// very generous temporary size !!!

	jpgbuff = (JOCTET*)memfile.GetData();

	/* Setup compression and do it */
	jpeg_memory_dest(&cinfo, jpgbuff, memfile.GetDataSize() );
	jpeg_set_defaults(&cinfo);
	jpeg_set_quality (&cinfo, quality, TRUE);
	jpeg_start_compress(&cinfo, TRUE);

	ImageBase	rgb_row( ImageBase::BF_R8G8B8, this->GetWidth(), 1 );
	
	/* compress each scanline one-at-a-time */
	while (cinfo.next_scanline < cinfo.image_height)
	{
		rgb_row.BlitFrom( *this, 0, cinfo.next_scanline, GetWidth(), 1, 0, 0 );

		JSAMPROW	lines[1] = { rgb_row.GetData() };

		jpeg_write_scanlines( &cinfo, lines, 1 );
	}
	
	jpeg_finish_compress(&cinfo);

	// Now extract the size of the compressed buffer
	mem_dest_ptr dest = (mem_dest_ptr)cinfo.dest;
	memfile.SetDataSize( dest->datacount );	// the actual compressed datasize

	// destroy the compressor handle
	jpeg_destroy_compress(&cinfo);
}
//=============================================================================
///
//=============================================================================
}
